package org.chen.bas.intercept;

import org.chen.auth.service.IPermissionService;
import org.chen.bas.context.LoginContext;
import org.chen.bas.solution.Qing;
import org.chen.org.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;
@Component
public class AuthIntercept implements HandlerInterceptor {
    @Autowired
    private IPermissionService service;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("认证，判断是否登录...........");
        String token = request.getHeader("token");
        if (Objects.isNull(token)){
            response.getWriter().write("{\"msg\":\"noLogin\",\"success\":false}");
            return false;
        }
        Employee employee = LoginContext.loginMap.get(token);
//        Employee employee = new Employee();
        if (Objects.isNull(employee)) {
            response.getWriter().write("{\"msg\":\"noLogin\",\"success\":false}");
            return false;
        }
//        1.判断传过来的接口是否需要权限
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        Qing annotation = method.getAnnotation(Qing.class);
        if (Objects.isNull(annotation)) {
            return true;
        }
//        2.需要权限-》通过用户查角色-》查用户权限。如果不需要，直接放行
//        2.1查询接口权限 ->sn 类名+方法名 -》controller + MethodName
        String name = method.getName();
        String simpleName = method.getDeclaringClass().getSimpleName();
        String s = simpleName + ":" + name;
//        2.2查询用户接口权限
        List<String> userSn= service.selectSnById(employee.getId());
        if (Objects.isNull(userSn)){
//            对于没有权限的要处理 跳到其他页面
            response.getWriter().write("{\"msg\":\"noPermission\",\"success\":false}");
            return false;
        }
//        2.3判断用户权限list中是否有接口的权限
        boolean contains = userSn.contains(s);
        if (! contains){
            response.getWriter().write("{\"msg\":\"noPermission\",\"success\":false}");
            return false;
        }
        return true;
    }
}
